package com.kern.rpcserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by caoshi at 21:12 2021-07-29
 */
public class RpcServer {


    private static final int CORE_POOL_SIZE = 5;        // 线程池中活跃线程数
    private static final int MAXIMUMPOOL_SIZE = 10;     // 线程池中最大线程数

    // 多余的空闲线程在终止之前等待新任务的最大时间
    private static final int KEEP_ALIVE_TIME = 200;


    // 用于接收客户端连接
    private ServerSocket serverSocket;
    // 连接端口
    private int serverPort;


    public RpcServer(int port) throws IOException {
        this.serverPort = port;
        this.serverSocket = new ServerSocket(this.serverPort);
    }


    /**
     * 使用线程池执行任务
     */
    public void start() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAXIMUMPOOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10));

        for (; ; ) {
            try {
                Socket socket = serverSocket.accept();
                RpcServerService rpcServerService = new RpcServerService(socket);
                executor.execute(rpcServerService);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
